//#include "typedefs.h"
#include <iostream>
#include <string.h>
#include "overqueue.h"

using namespace std;

OverQueue::OverQueue(int msize) : _front(0), _size(0), maxsize(msize)
{
	//maxsize = msize;
	_queue = new int[msize];

	cout << "overqueue constructor!" << endl;
}

bool OverQueue::enqueue(int *data)
{
	if(_size >= maxsize)
	{
		cout << "OverQueue full" << endl;
		return false;
	}

	_size++;
	_queue[(_front + _size) % maxsize] = *data;

	return true;
}
 
int* OverQueue::get_head(void)
{
	if(empty())
	{
		cout << "OverQueue empty!" << endl;
		return NULL;
	}

	return &_queue[(_front + 1) % maxsize];
}

int* OverQueue::get_tail(void)
{
	if(empty())
	{
		cout << "OverQueue empty!" << endl;
		return NULL;
	}

	return &_queue[(_front + _size) % maxsize];
}

int* OverQueue::get_by_index(unsigned int index)
{
	if(empty())
	{
		cout << "OverQueue empty!" << endl;
		return NULL;
	}

	if(index < 1) return NULL;
	if((int)index <= _size) return &_queue[(_front+index)%maxsize];

	return NULL;
}

void OverQueue::remove_head(void)
{
	if(empty()) return;

	_front = (_front + 1)%maxsize;
	memset(&_queue[_front], 0, sizeof(int));

	if(_size > 0) _size--;
}

void OverQueue::remove_tail(void)
{
	if(empty()) return;

	memset(&_queue[(_front+_size)%maxsize], 0, sizeof(int));

	if(_size > 0) _size--;
}

//test
#include "sort_algorithm.h"

void overqueue_test(void)
{
    int i = 0;
    OverQueue queue(10);

    for(i = 18; i >= 7; i--)
    {
        queue.enqueue(&i);
    }

    cout << "size" << queue.size() << endl;
    cout << "head=" << *queue.get_head() << endl;
    cout << "rear=" << *queue.get_tail() << endl;

    queue.remove_tail();
    queue.remove_head();

    cout << queue.size() << endl;
    cout << "head=" << *queue.get_head() << endl;
    cout << "rear=" << *queue.get_tail() << endl;

    for(i = 34; i < 35; i++) queue.enqueue(&i);

    for(i = 1; i <= queue.size(); i++)
        cout << *queue.get_by_index(i) << " ";

    cout << endl;
}
